class SignalingServer {
  constructor(wss) {
    this.wss = wss;
  }

  handleSignal(ws, message, clients) {
    const { to, from, signal, signalType } = message;

    // Find the recipient
    const recipient = clients.get(to);

    if (recipient && recipient.ws.readyState === 1) {
      // Forward the WebRTC signaling message
      recipient.ws.send(JSON.stringify({
        type: 'webrtc-signal',
        from: from,
        signal: signal,
        signalType: signalType, // 'offer', 'answer', or 'ice-candidate'
        timestamp: Date.now()
      }));

      // Confirm delivery to sender
      ws.send(JSON.stringify({
        type: 'signal-delivered',
        to: to,
        signalType: signalType
      }));
    } else {
      // Recipient not available
      ws.send(JSON.stringify({
        type: 'signal-failed',
        to: to,
        reason: 'Recipient offline'
      }));
    }
  }

  // Handle call initiation
  handleCallRequest(ws, message, clients) {
    const { to, from, callType } = message; // callType: 'audio' or 'video'

    const recipient = clients.get(to);

    if (recipient && recipient.ws.readyState === 1) {
      // Notify recipient of incoming call
      recipient.ws.send(JSON.stringify({
        type: 'incoming-call',
        from: from,
        callType: callType,
        timestamp: Date.now()
      }));

      // Confirm to caller
      ws.send(JSON.stringify({
        type: 'call-ringing',
        to: to
      }));
    } else {
      ws.send(JSON.stringify({
        type: 'call-failed',
        to: to,
        reason: 'Recipient offline'
      }));
    }
  }

  // Handle call acceptance/rejection
  handleCallResponse(ws, message, clients) {
    const { to, from, signalType, signal } = message;

    const caller = clients.get(to);

    if (caller && caller.ws.readyState === 1) {
      // Forward the response signal
      caller.ws.send(JSON.stringify({
        type: 'webrtc-signal',
        from: from,
        signalType: signalType,
        signal: signal,
        timestamp: Date.now()
      }));
    } else {
      // Notify sender if caller is not available
      ws.send(JSON.stringify({
        type: 'call-failed',
        to: to,
        reason: 'Caller offline'
      }));
    }
  }
}

module.exports = SignalingServer;
